package com.zj.inoutput.web;

import com.zj.inoutput.common.ResultData;
import com.zj.inoutput.model.request.ExportGetListParam;
import com.zj.inoutput.model.request.ExportParam;
import com.zj.inoutput.service.ExportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author DuanYu <a>Email:z-houjie@qq.com</a>
 * @date 2022-02-08 11:22
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/export")
public class ExportController {

    private final ExportService exportService;

    /**
     * 上传
     *
     * @param file 文件
     */
    @PostMapping("/upload")
    public void upload(MultipartFile file) {
        Assert.isTrue(Objects.requireNonNull(file.getOriginalFilename()).endsWith(".xlsx"), "请以.xlsx格式导入文件");
        exportService.upload(file);
    }

    /**
     * 查询数据入库
     *
     * @param param 请求参数
     */
    @PostMapping("/data")
    public void export(@RequestBody ExportParam param) {
        // 对于参数校验,懒的引包 没写
        exportService.exportExcel(param);
        log.info("数据制作中...");
    }

    /**
     * 获取导出列表
     *
     * @param param 请求参数
     * @return
     */
    @PostMapping("/get")
    public ResultData getExportList(@RequestBody @Validated ExportGetListParam param) {
        // 对于参数校验,懒的引包 没写
        return ResultData.successful(exportService.findExportList(param));
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable Integer id, HttpServletResponse response) throws IOException {
        exportService.download(id, response);
    }
}
